#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "double_linkedlist.h"

// 数据结构定义
typedef struct Person {
    char name[50];
    int age;
} Person;

// 比较函数，用于查找和删除元素
int compare_person(const void *data, const void *key) 
{
    return strcmp(((Person *)data)->name, ((Person *)key)->name);
}

// 打印函数，用于遍历链表时打印数据
void print_person(const void *data)
{
    const Person *person = (const Person *)data;
    printf("Name: %s, Age: %d\n", person->name, person->age);
}

int main()
{
    dlisthead_t *list = NULL;
    int ret;
    
    // 初始化链表
    ret = dlisthead_init(&list, sizeof(Person));
    if (ret != 0) {
        printf("Failed to initialize list\n");
        return -1;
    }

    // 插入数据：头插法
    Person p1 = {"Alice", 30};
    ret = dlist_insert(list, &p1);
    if (ret != 0) {
        printf("Failed to insert Alice\n");
    }

    Person p2 = {"Bob", 25};
    ret = dlist_insert(list, &p2);
    if (ret != 0) {
        printf("Failed to insert Bob\n");
    }

    // 插入数据：尾插法
    Person p3 = {"Charlie", 35};
    ret = dlist_insert_tail(list, &p3);
    if (ret != 0) {
        printf("Failed to insert Charlie\n");
    }

    Person p4 = {"David", 40};
    ret = dlist_insert_tail(list, &p4);
    if (ret != 0) {
        printf("Failed to insert David\n");
    }

    // 遍历链表并打印
    printf("Traverse list:\n");
    dlist_traval(list, print_person);

    // 查找元素：查找Bob
    Person key = {"Bob", 0};  // 只关心名字
    Person *found_person = (Person *)dlist_search(list, &key, compare_person);
    if (found_person) {
        printf("Found person: Name: %s, Age: %d\n", found_person->name, found_person->age);
    } else {
        printf("Person not found\n");
    }

    // 删除元素：删除Charlie
    Person delete_key = {"Charlie", 0};
    ret = dlist_delete(list, &delete_key, compare_person);
    if (ret == 0) {
        printf("Deleted Charlie\n");
    } else {
        printf("Failed to delete Charlie\n");
    }

    // 遍历链表并打印
    printf("Traverse list after deletion:\n");
    dlist_traval(list, print_person);

    // 销毁链表
    dlist_destroy(&list);
    printf("List destroyed\n");

    return 0;
}

